<?php

namespace plugin\webman\gateway;

use common\service\JwtService;
use core\constants\GatewayConst;
use core\exception\BadException;
use core\utils\WsUtil;
use GatewayWorker\Lib\Gateway;
use Throwable;

class Events
{
    public static function onWorkerStart($worker)
    {

    }

    public static function onConnect($client_id)
    {
    }

    public static function onWebSocketConnect($client_id, $data)
    {
        //验证token是否正常 正常后加入admin组以及绑定用户
        $user = [];
        try {
            $token = $data['get']['token'] ?? "";
            if (!$token) {
                throw new BadException("鉴权异常");
            }
            $user = JwtService::verifyToken($data['get']['token'], 'admin');
        } catch (Throwable $exception) {
            Gateway::sendToClient($client_id, WsUtil::encode("login", [
                "msg" => "鉴权异常"
            ]));
            Gateway::closeClient($client_id);
        }

        $uid = $user['id'] ?? 0;
        if ($uid) {
            Gateway::bindUid($client_id, $uid);
            Gateway::joinGroup($client_id, GatewayConst::ADMIN_GROUP);
            Gateway::sendToUid($uid, WsUtil::encode("login", [
                "msg" => "链接成功"
            ]));
        }
    }

    public static function onMessage($client_id, $message)
    {
        if ($message === '{"cmd":"ping"}') {
            return;
        }

    }

    public static function onClose($client_id)
    {
        Gateway::leaveGroup($client_id, GatewayConst::ADMIN_GROUP);
    }

}
